package com.peng.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.peng.constant.Constants;
import com.peng.model.TActivity;
import com.peng.model.TUser;
import com.peng.query.ActivityQuery;
import com.peng.query.BaseQuery;
import com.peng.result.R;
import com.peng.service.TActivityService;
import com.peng.util.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
public class ActivityController {

    @Autowired
    private TActivityService tActivityService;

    //以分页形式进行多个市场活动的查询
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/api/activitys")   //required = false 表示参数可传不穿，反之必须穿
    public R userPage(@RequestParam(value="current",required = false) Integer current,
                      @ModelAttribute ActivityQuery activityQuery) {
        //当没传入参数时，初始化为1
        if(current == null) {current = 1;}
        System.out.println(activityQuery);
        IPage<TActivity> tActivityIPage = tActivityService
                .selectActivityIPage(activityQuery,
                        new Page<TActivity>(current, Constants.PAGE_SIZE));
        return R.OK(tActivityIPage);
    }

    //获取指定 id 编号的活动信息
    @GetMapping(value = "/api/activity/{id}")
    public R loadActivity(@PathVariable(value = "id") Integer id) {
        TActivity tActivity = tActivityService.getActivityById(id);
        return R.OK(tActivity);
    }

    //编辑活动
    @PutMapping(value = "/api/activity")
    public R editActivity(@ModelAttribute ActivityQuery activityQuery, @RequestHeader(value = "Authorization") String token) {

        TActivity tActivity = new TActivity();

        BeanUtils.copyProperties(activityQuery, tActivity);
        //编辑人id
        tActivity.setEdit_by(JWTUtils.parseUserFromJWT(token).getId());
        //编辑时间
        tActivity.setEdit_time(new Date());

        boolean update = tActivityService.updateById(tActivity);
        return update ? R.OK() : R.FAIL();
    }

    //录入活动
    @PostMapping(value = "/api/activity")
    public R addActivity(@ModelAttribute ActivityQuery activityQuery, @RequestHeader(value = "Authorization") String token) {

        TActivity tActivity = new TActivity();

        BeanUtils.copyProperties(activityQuery, tActivity);
        //创建人id
        tActivity.setCreate_by(JWTUtils.parseUserFromJWT(token).getId());
        //创建时间
        tActivity.setCreate_time(new Date());

        boolean save = tActivityService.save(tActivity);
        return save ? R.OK() : R.FAIL();
    }
}
